package message

import (
	"gomonitor-server/src/mylog"
	"gomonitor-server/src/tcp/types"
	"gomonitor-server/src/util"
	"net"
)

func (messageHandler *MessageHandler) SendMessage(msgFrom byte, data []byte, msgType byte, conn net.Conn) {
	dataLen := len(data)
	dataLenBytes := util.Int2Bytes(uint32(dataLen))
	msgLen := 14 + dataLen
	msgBuffer := make([]byte, msgLen)
	//header
	copy(msgBuffer[0:4], types.MsgHeaderBytes)
	//上下行
	copy(msgBuffer[4:5], []byte{msgFrom})
	//类型
	copy(msgBuffer[5:6], []byte{msgType})
	//数据长度
	copy(msgBuffer[6:6+4], dataLenBytes)
	//数据
	copy(msgBuffer[6+4:6+4+dataLen], data)
	checkSum := util.CalculateChecksum(data)
	checkSumBytes := util.Int2Bytes(checkSum)
	//数据校验
	copy(msgBuffer[6+4+dataLen:6+4+dataLen+4], checkSumBytes)
	bufferSize := 1024
	if len(msgBuffer) <= bufferSize {
		_, err := conn.Write(msgBuffer)
		if err != nil {
			mylog.Logger.Errorf("1向%s发送消息,类型:%d,长度:%d, 失败:%s", conn.RemoteAddr().String(), msgType, msgLen, err.Error())
			return
		}
	} else {
		for i := 0; i < len(msgBuffer); i += bufferSize {
			end := i + bufferSize
			if end > len(msgBuffer) {
				end = len(msgBuffer)
			}
			chunk := msgBuffer[i:end]
			_, err := conn.Write(chunk)
			if err != nil {
				mylog.Logger.Errorf("2向%s发送消息,类型:%d,长度:%d, 失败:%s", conn.RemoteAddr().String(), msgType, msgLen, err.Error())
				return
			}
		}
	}
	mylog.Logger.Debugf("向%s发送消息,类型:%d,长度:%d,成功", conn.RemoteAddr().String(), msgType, msgLen)
}
